package org.zxp.datastructure.map.lru;

import org.junit.Test;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @program: effectiveJava
 * @description: 增强LinkedHashMap以实现LRU
 * @author: X-Pacific zhang
 * @create: 2019-07-24 10:27
 **/
public class LinkedHashMapLRU<K,V> extends LinkedHashMap<K,V> {
    private int capacity = 0;
    //不能用读写锁，因为读并发时双向链表会有线程安全性问题
//    private ReadWriteLock lock = new ReentrantReadWriteLock();
//    private Lock readLock;
//    private Lock writeLock;
    private Lock lock = new ReentrantLock();

    public LinkedHashMapLRU(int capacity) {
        super(capacity,0.75f,true);
        this.capacity = capacity;
//        readLock = lock.readLock();
//        writeLock = lock.writeLock();
    }

    @Override
    public V put(K key,V value){
        lock.lock();
        try{
            return super.put(key,value);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public V get(Object key){
        lock.lock();
        try{
            return super.get(key);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public V remove(Object key){
        lock.lock();
        try{
            return super.remove(key);
        }finally {
            lock.unlock();
        }
    }


    @Override
    public boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        if(size() > capacity) {
            return true;
        }
        return false;
    }

    public void print(){
        super.forEach((k,v) -> System.out.println(k+"="+v));
        System.out.println();
    }
}
